<template>
	<div>
		<van-popup safe-area-inset-bottom round :show="show" position="bottom">
			<div class="inner">
				<div class="top">
					<div class="tit"><span>余额不足</span>请充值</div>
					<div class="cancel" @click="handleCancle">取消</div>
				</div>
				<div class="middle">
					<div class="tit">充值套餐</div>
					<!-- <div class="price-cont">
            <div class="icon">￥</div>
            <van-field v-model="price" class="inputinfo" :border="false" placeholder="请输入金额" type="number" />
            <div class="text">
              实得金额：<span style="color: #f5222d">{{ price }}</span>
            </div>
          </div> -->
				</div>
				<div class="footer">
					<!-- <div class="desc">充值满500送价值129业务通会员一年</div> -->
					<div class="btncont">
						<div :class="`pricebtn ${price == item.price ? 'activebg' : ''}`" v-for="(item, index) in list"
							@click="handlePrice(item)">
							{{ item.price }}元
						</div>
					</div>

					<!-- <div class="jiedan" v-if="procuresid">
            <van-checkbox v-model="jiedan" class="scheck" shape="square" icon-size="14">充值完成后立即接单</van-checkbox>
          </div> -->
				</div>
				<div class="" style="margin-top: 15px;">
					<van-field v-model="price" label="自定义金额" type="digit" placeholder="请输入金额" />
				</div>
				<div class="recharge">
					<van-button type="success" block @click="handleSubmit">确认充值</van-button>
				</div>
			</div>
		</van-popup>
		<BindPhone :show="bindPhoeShoe" @cancel="handlePhoneCancel" @confirm="handleBindPhoneConfirm"></BindPhone>
	</div>
</template>
<script setup lang="ts">
	import { defineEmits, ref } from "vue";
	import { Checkbox, showToast, showLoadingToast } from "vant";
	import { buypackagesApi, wechatpayvApi, userphoneApi } from "@/api/detail";
	import { userInfoApi } from '@/api/user'
	import { BindPhone } from "@/components";
	import { getCookie } from "@/utils";
	const emit = defineEmits(["cancel"]);
	interface Props {
		show : boolean;
		procuresid ?: string;
	}
	const moneyValue = ref();
	const props = withDefaults(defineProps<Props>(), {
		show: false,
	});
	const bindPhoeShoe = ref(false)
	const jiedan = ref(true);
	const price = ref<any>('');
	const list = ref<Array<any>>([]);
	const getlist = async () => {
		let { data } = await buypackagesApi({});
		list.value = data || [];
		if (list.value.length) {
			price.value = list.value[0].price;
		}
	};
	getlist();

	const handleCancle = () => {
		jiedan.value = true;
		price.value = "";
		emit("cancel");
	};
	const handleSubmit = async () => {

		if (!price.value) {
			showToast({
				message: "请输入金额",
				position: "top",
			});

			return;
		}
		let { data: userData } = await userInfoApi({ uid: getCookie('token') ? Number(getCookie('token')) : '' })
		localStorage.removeItem('userInfo')
		localStorage.setItem('userInfo', JSON.stringify(userData))
		if (!userData.phone) {
			bindPhoeShoe.value = true
			return
		}
		let { data, code } = await wechatpayvApi({
			uid: getCookie("token") ? Number(getCookie("token")) : '',
			price: Number(price.value),
		});
		let loading = showLoadingToast({
			duration: 0,
			message: '加载中...',
			forbidClick: true,
		});
		if (code == 0 && data?.paySign) {
			loading.close()
			handleCancle()
			WeixinJSBridge.invoke(
				"getBrandWCPayRequest",
				{
					appId: data.appId, //公众号ID，由商户传入
					timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
					nonceStr: data.nonceStr, //随机串
					package: data.package,
					signType: data.signType, //微信签名方式：
					paySign: data.paySign,
				},
				function (res : any) {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						// 使用以上方式判断前端返回,微信团队郑重提示：
						//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						location.reload();
					}
					if (res.err_msg === "get_brand_wcpay_request:cancel") {
						showToast({
							message: "支付取消",
							position: "top",
						});

						return;
					}
					if (res.err_msg === "get_brand_wcpay_request:fail") {
						showToast({
							message: "支付失败",
							position: "top",
						});

						return;
					}
				}
			);

		} else {
			loading.close()
			showToast({
				message: "拉取支付失败",
				position: "top",
			});

			return;
		}
	};
	const handlePrice = (data : any) => {
		price.value = data.price;
	};
	const handlePhoneCancel = () => {
		bindPhoeShoe.value = false
	}
	const handleBindPhoneConfirm = async (phone : string) => {
		bindPhoeShoe.value = false
		let loading = showLoadingToast({
			duration: 0,
			message: '请稍后...',
			forbidClick: true,
		});
		let { code, msg } = await userphoneApi({ uid: getCookie("token") ? Number(getCookie("token")) : '', phone })
		if (code === 0) {
			loading.close()
			handleSubmit()
		} else {
			showToast({
				message: msg,
				position: 'top'
			})
		}

	}
	// const onInput = (event:any)=> {
	// 	// const value = event.detail;
	// 	price.value = event.detail;
	// }
</script>
<style lang="scss" scoped>
	.inner {
		padding: 15px 15px 20px 15px;
		color: #333;

		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.tit {
				span {
					color: #f5222d;
				}
			}

			.cancel {
				color: #999;
			}
		}

		.middle {
			margin-top: 15px;

			.tit {
				font-size: 13px;
				color: #999;
			}

			.price-cont {
				display: flex;
				align-items: center;
				border-bottom: 1px solid #edf0f2;
				margin-top: 5px;

				.icon {
					font-size: 16px;
					font-weight: 500;
					flex-shrink: 0;
				}

				.inputinfo {
					flex: 1;
					font-size: 16px;
				}

				.text {
					flex-shrink: 0;
					// padding: 0 5px;
				}
			}
		}

		.footer {
			margin-top: 15px;

			.desc {
				font-size: 12px;
				color: #f5222d;
			}

			.btncont {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				margin-top: 10px;

				.pricebtn {
					margin-bottom: 5px;
					width: calc(33.33% - 5px);
					display: flex;
					align-items: center;
					justify-content: center;
					border: 1px solid #07c160;
					color: #07c160;
					height: 44px;
					border-radius: 4px;
				}

				.activebg {
					background-color: #07c160;
					color: #fff;
				}
			}

			.jiedan {
				margin-top: 5px;

				.scheck {
					font-size: 13px;
					color: #999 !important;
				}

				:deep .van-checkbox__label {
					font-size: 12px;
					color: #999 !important;
				}
			}
		}

		.recharge {
			margin-top: 15px;
		}
	}
</style>